﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using OpenPop.Pop3;
using OpenPop.Mime;
using OpenPop.Common.Logging;
using OpenPop.Pop3.Exceptions;
using cecbData;
using System.Threading;
using System.Runtime.Remoting.Messaging;
using Microsoft.Win32;
using System.IO;
using System.Net;
using System.Configuration;
using System.Windows.Media.Animation;
using System.Data;

using cecbClasses.Data_Classes;


namespace CECB
{
    /// <summary>
    /// Interaction logic for V_EmailReader_Window.xaml
    /// </summary>
    public partial class V_EmailReader_Window : Window
    {

        private readonly Dictionary<int, Message> messages = new Dictionary<int, Message>();
        private readonly Pop3Client pop3Client;
        int success = 0;
        int count;

        private List<MailMassage> mailListALL;
        private List<MailMassage> mailListNew;
        private List<MailMassage> filterdListAll;
        private List<MailMassage> filterdListNew;

        public delegate void ReceiveMailsDelegate();
        public SaveFileDialog savefile;
        private int LastEmailID = -1;

        private bool isRefreshing = false;
        private bool isNewMailClicked = false;
        private bool isAllMailClicked = false;


        public V_EmailReader_Window()
        {
            InitializeComponent();
            pop3Client = new Pop3Client();
            TextBlockNewMailNotify.Visibility = System.Windows.Visibility.Hidden;
            ProjectAutocompleteTextBox.DataContext = new DSSEntities().Projects;
        }


        public void OnCompletionReceiveMails(IAsyncResult res)
        {

            AsyncResult result = (AsyncResult)res;
            ReceiveMailsDelegate initialDel = (ReceiveMailsDelegate)result.AsyncDelegate;

            if (result.EndInvokeCalled == false)
            {

            }

        }

        private bool CheckConnection()
        {
            WebClient client = new WebClient();
            try
            {
                using (client.OpenRead("http://www.google.com"))
                {
                    labelInternetConnectionStatus.Content = "Internet Connection Available";
                    labelInternetConnectionStatus.Background = Brushes.Green;
                }
                return true;
            }
            catch (WebException)
            {
                labelInternetConnectionStatus.Content = "No Internet Connection Found!";
                labelInternetConnectionStatus.Background = Brushes.Red;


                MessageBox.Show("Please Check Your Internet Connection! ");
                return false;
            }
        }

        private bool CheckConnectionLoop()
        {
            WebClient client = new WebClient();
            try
            {
                using (client.OpenRead("http://www.google.com"))
                {
                    labelInternetConnectionStatus.Content = "Internet Connection Available";
                    labelInternetConnectionStatus.Background = Brushes.Green;
                }
                return true;
            }
            catch (WebException)
            {
                labelInternetConnectionStatus.Content = "No Internet Connection Found!";
                labelInternetConnectionStatus.Background = Brushes.Red;


                return false;
            }
        }

        private void RefreshEmailButton_Click(object sender, RoutedEventArgs e)
        {


        }

        private void getEmailsFromSever()
        {

            try
            {
                String value = ConfigurationManager.AppSettings["NewMailID"].ToString();
                LastEmailID = int.Parse(value);

                if (LastEmailID <= 0)
                {

                    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    config.AppSettings.Settings["NewMailID"].Value = 1 + "";
                    config.Save(ConfigurationSaveMode.Modified);
                    ConfigurationManager.RefreshSection("appSettings");
                }
                if (LastEmailID > 0)
                {
                    if (CheckConnection())
                    {

                        mailListALL = new List<MailMassage>();
                        mailListNew = new List<MailMassage>();
                        ReceiveMailsDelegate del = ReceiveMails;
                        AsyncCallback callback = OnCompletionReceiveMails;
                        del.BeginInvoke(callback, null);

                    }
                }


            }
            catch (Exception)
            {


            }

        }

        private void getEmailBody(int key)
        {
            Message msj = messages[key];

            labelMailHeader.Content = "Header : " + msj.Headers.Subject.ToString();
            ExpanderComments.Header = "Comments by : " + msj.Headers.From.ToString();

            MessagePart selectedMessagePart = msj.MessagePart;
            if (selectedMessagePart is MessagePart)
            {
                if (selectedMessagePart.IsText)
                {
                    // We can show text MessageParts
                    TextBoxBody.Text = selectedMessagePart.GetBodyAsText();
                    labelMailHeader.Content = "Header : " + msj.Headers.Subject.ToString();
                    ExpanderComments.Header = "Comments by : " + msj.Headers.From.ToString();
                }
                else
                {
                    // We are not able to show non-text MessageParts (MultiPart messages, images, pdf's ...)
                    TextBoxBody.Text = "<<OpenPop>> Cannot show this part of the email. It is not text <<OpenPop>>";
                }

            }

            // Find the first text/plain version
            MessagePart plainTextPart = msj.FindFirstPlainTextVersion();
            if (plainTextPart != null)
            {
                // The message had a text/plain version - show that one
                TextBoxBody.Text = plainTextPart.GetBodyAsText();
            }
            else
            {
                // Try to find a body to show in some of the other text versions
                List<MessagePart> textVersions = msj.FindAllTextVersions();
                if (textVersions.Count >= 1)
                    TextBoxBody.Text = textVersions[0].GetBodyAsText();
                else
                    TextBoxBody.Text = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>";
            }


            List<MessagePart> textVersions1 = msj.FindAllTextVersions();
            //if (textVersions1.Count >= 1)
            //    webBrowser1.NavigateToString(textVersions1[0].GetBodyAsText());
        }

        private void getEmailAttachments(int key)
        {
            Message msj = messages[key];
            List<MessagePart> attachments = msj.FindAllAttachments();
            if (attachments.Count > 0)
            {
                textBox1.Content = attachments[0].FileName.ToString();
                textBox1.Background = Brushes.Green;
                textBox1.Foreground = Brushes.White;
            }
            else
            {
                textBox1.Content = " No Attachments Available! ";
                textBox1.Background = Brushes.Red;
                textBox1.Foreground = Brushes.White;
            }
        }


        private String dlfilePath;

        private void downloadAttachment(int key)
        {

            Message msj = messages[key];
            List<MessagePart> attachments = msj.FindAllAttachments();

            if (textBox1.Content.ToString().Length != 0)
            {

                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();

                dlg.FileName = attachments[0].FileName;

                Nullable<bool> result = dlg.ShowDialog();


                if (result == true)
                {
                    dlfilePath = dlg.FileName;

                    FileInfo file = new FileInfo(dlg.FileName);

                    if (file.Exists)
                    {

                        file.Delete();
                    }

                    try
                    {
                        attachments[0].Save(file);

                        MessageBox.Show(this, "Attachment saved successfully");
                    }
                    catch (Exception)
                    {
                        MessageBox.Show(this, "Attachment saving failed. Exception message: ");
                    }
                }
            }
            else
            {
                MessageBox.Show(this, "Attachment object was null!");
            }


        }

        private void OkClick(object sender, RoutedEventArgs e)
        {

        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            String value = ConfigurationManager.AppSettings["NewMailID"].ToString();
            MessageBox.Show(value);

        }

        private void RefreshMailBox_Click(object sender, RoutedEventArgs e)
        {
            if (!isRefreshing)
            {
                isRefreshing = true;
                getEmailsFromSever();

            }
        }

        private void NewMailButton_Click(object sender, RoutedEventArgs e)
        {
            if (!isNewMailClicked)
            {

                isNewMailClicked = true;
                isAllMailClicked = false;
                NewMailButton.Background = Brushes.Gray;

                var converter = new System.Windows.Media.BrushConverter();
                var brush = (Brush)converter.ConvertFromString("#FF3E3832");
                AllMailButton.Background = brush;



                listBoxNewEmails.Visibility = System.Windows.Visibility.Visible;
                listBoxAllEmails.Visibility = System.Windows.Visibility.Hidden;

                try
                {
                    listBoxNewEmails.ItemsSource = null;
                    listBoxNewEmails.ItemsSource = mailListNew;

                }
                catch (Exception)
                {


                }
            }

        }

        private void AllMailButton_Click(object sender, RoutedEventArgs e)
        {

            //   (FindResource("SlideCanvasRL") as Storyboard).Begin(this);

            if (!isAllMailClicked)
            {
                isAllMailClicked = true;
                isNewMailClicked = false;
                AllMailButton.Background = Brushes.Gray;

                var converter = new System.Windows.Media.BrushConverter();
                var brush = (Brush)converter.ConvertFromString("#FF3E3832");
                NewMailButton.Background = brush;


                listBoxNewEmails.Visibility = System.Windows.Visibility.Hidden;
                listBoxAllEmails.Visibility = System.Windows.Visibility.Visible;


                try
                {
                    listBoxAllEmails.ItemsSource = null;
                    listBoxAllEmails.ItemsSource = mailListALL;

                }
                catch (Exception)
                {


                }

            }
        }

        private void ReferenceTextBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                filterdListAll = new List<MailMassage>();
                String refe = ProjectAutocompleteTextBox.Text;
                if (mailListALL.Count > 0)
                {
                    foreach (MailMassage msj in mailListALL)
                    {
                        if (msj.MessageSubject.Contains(refe))
                        {
                            filterdListAll.Add(msj);
                        }

                    }

                }

                filterdListNew = new List<MailMassage>();
                if (mailListNew.Count > 0)
                {
                    foreach (MailMassage msj in mailListNew)
                    {
                        if (msj.MessageSubject.Contains(refe))
                        {
                            filterdListNew.Add(msj);
                        }

                    }
                }


                listBoxNewEmails.ItemsSource = null;

                listBoxNewEmails.ItemsSource = filterdListNew;

                listBoxAllEmails.ItemsSource = null;

                listBoxAllEmails.ItemsSource = filterdListAll;

            }
            catch (Exception)
            {


            }
        }

        private int item;
        private void listBoxAllEmails_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox lbx = (ListBox)sender;
            item = lbx.SelectedIndex;


            if (item > -1)
            {
                int msjKey = mailListALL[item].MsjID;
                getEmailBody(msjKey);
                getEmailAttachments(msjKey);
            }
        }


        private void ReceiveMails()
        {

            try
            {
                if (pop3Client.Connected)
                    pop3Client.Disconnect();
                pop3Client.Connect("pop.gmail.com", 995, true);
                // pop3Client.Authenticate("gayashan.gzn@gmail.com", "BlackBook.NET4.0");
                pop3Client.Authenticate("chooty1001@gmail.com", "900760922v");
                //     pop3Client.Authenticate("lakshi.jayasuriya@gmail.com", "<3jabtakhaijaan");
                count = pop3Client.GetMessageCount();
                int count1 = pop3Client.GetMessageCount();
                int y = count - LastEmailID;
                messages.Clear();


                this.Dispatcher.Invoke((Action)(() =>
                {
                    textBloackAllMailCount.Text = "Total Emails " + count;
                    if (y > 0)
                    {
                        TextBlockNewMailNotify.Text = y + "";
                        TextBlockNewMailNotify.Visibility = System.Windows.Visibility.Visible;
                    }
                }));



                int fail = 0;
                // for (int i = count; i >= 1; i -= 1)
                //if (IsOnlyNewMaile) {
                //    MailMax = LastEmailID + 1;
                //}
                //else if (!IsOnlyNewMaile) {
                //    MailMax = 1;
                //}


                for (int i = count; i >= 1; i -= 1)
                {

                    bool Status = false;
                    this.Dispatcher.Invoke((Action)(() =>
                    {
                        Status = CheckConnectionLoop();
                    }));

                    if (Status)
                    {
                        try
                        {

                            Message message = pop3Client.GetMessage(i);
                            messages.Add(i, message);
                            mailListALL.Add(new MailMassage(message.Headers.DateSent.ToLongDateString(), message.Headers.From.ToString(), message.Headers.Subject.ToString(), message, i));

                            if (i > LastEmailID)
                                mailListNew.Add(new MailMassage(message.Headers.DateSent.ToLongDateString(), message.Headers.From.ToString(), message.Headers.Subject.ToString(), message, i));

                            success++;

                            this.Dispatcher.Invoke((Action)(() =>
                            {

                                listBoxAllEmails.ItemsSource = null;
                                listBoxAllEmails.ItemsSource = mailListALL;

                                listBoxNewEmails.ItemsSource = null;
                                listBoxNewEmails.ItemsSource = mailListNew;

                                int val1 = (int)(((double)(count - i + 1) / count) * 100);
                                progressBarRefresh.Value = val1;
                                if (val1 >= 100)
                                {
                                    textBloackAllMailCountProgress.Text = " 100% Complete";
                                }
                                else
                                {
                                    textBloackAllMailCountProgress.Text = " " + val1 + "% Complete";
                                }

                                int val2 = (int)(((double)((count - LastEmailID) - y) / (count - LastEmailID)) * 100);
                                y--;
                                progressBarNewMail.Value = val2;
                                if (val2 >= 100)
                                {
                                    textBloackNewMailCountProgress.Text = " 100% Complete";
                                }
                                else
                                {
                                    textBloackNewMailCountProgress.Text = " " + val2 + "% Complete";
                                }
                                //label2.Content = success + "";

                            }));


                        }
                        catch (Exception e)
                        {

                            MessageBox.Show("DDD  " + e.Message.ToString());
                            DefaultLogger.Log.LogError(
                                "TestForm: Message fetching failed: " + e.Message + "\r\n" +
                                "Stack trace:\r\n" +
                                e.StackTrace);
                            fail++;
                        }

                    }
                    else
                    {
                        MessageBox.Show("No internet found");
                        return;
                    }


                }
                if (fail > 0)
                {
                    MessageBox.Show(this,
                                    "Since some of the emails were not parsed correctly (exceptions were thrown)\r\n" +
                                    "please consider sending your log file to the developer for fixing.\r\n" +
                                    "If you are able to include any extra information, please do so.",
                                    "Help improve OpenPop!");
                }
            }
            catch (InvalidLoginException)
            {
                MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication");
            }
            catch (PopServerNotFoundException)
            {
                MessageBox.Show(this, "The server could not be found", "POP3 Retrieval");
            }
            catch (PopServerLockedException)
            {
                MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked");
            }
            catch (LoginDelayException)
            {
                MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay");
            }
            catch (Exception e)
            {
                //MessageBox.Show(this, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval");
            }
            finally
            {
                // Enable the buttons again
                //  isRefreshing = false;
            }

        }

        private void image1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            int msjKey = 1;

            if (item > -1)
            {
                msjKey = mailListALL[item].MsjID;
                downloadAttachment(msjKey);
            }

            String value = ConfigurationManager.AppSettings["NewMailID"].ToString();
            LastEmailID = int.Parse(value);

            int DlMailId = int.Parse(msjKey.ToString());

            if (DlMailId > LastEmailID)
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.AppSettings.Settings["NewMailID"].Value = msjKey.ToString();
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
            }
        }

        private void ConfrirmDetails_Click(object sender, RoutedEventArgs e)
        {
            FileInfo fi = new FileInfo(dlfilePath);
            if (fi.Exists)
            {
                System.Diagnostics.Process.Start(dlfilePath);
            }
        }

        private void FilerDetails_Click(object sender, RoutedEventArgs e)
        {
            String filePath = "";

            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = "Document"; // Default file name 
            dlg.DefaultExt = ".xlsx"; // Default file extension 
            dlg.Filter = "Excel documents (.xlsx)|*.xlsx"; // Filter files by extension 

            // Show open file dialog box 
            Nullable<bool> result = dlg.ShowDialog();

            // Process open file dialog box results 
            if (result == true)
            {
                // Open document 
                filePath = dlg.FileName;
            }
            else
                return;

            //  MessageBox.Show(filePath);


            bool isSimpleMtrix = new cecbClasses.Data_Adapters.Excel.ReadExcel().getMatrixType(filePath);
            if (isSimpleMtrix)
            {
                List<cecbClasses.Data_SimpleMatrixValues> lstnew = new cecbClasses.Data_Adapters.Excel.ReadExcel().getValuesSimpleMatrix(filePath);

                SimpleMatrixlistBoxEmailValues.ItemsSource = lstnew;
                SimpleMatrixlistBoxEmailValues.Visibility = System.Windows.Visibility.Visible;
                listBoxEmailValues.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {

                List<cecbClasses.Data_LeopoldMatrixValues> lstnew = new cecbClasses.Data_Adapters.Excel.ReadExcel().getValues(filePath);

                listBoxEmailValues.ItemsSource = lstnew;

                SimpleMatrixlistBoxEmailValues.Visibility = System.Windows.Visibility.Hidden;
                listBoxEmailValues.Visibility = System.Windows.Visibility.Visible;
            }




            // new FillMatrix_Window(lstnew , prj,lstAct,lstImp).ShowDialog();
        }

        private void listBoxActivities_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                cecbClasses.Data_LeopoldMatrixValues dat;
                dat = (cecbClasses.Data_LeopoldMatrixValues)listBoxEmailValues.SelectedItem;
                int x = listBoxEmailValues.SelectedIndex;




                //MessageBox.Show(dat.Actv_reference.ToString());
                String impact = dat.Impt_reference.ToString();
                String activ = dat.Actv_reference.ToString();
                String val1 = dat.Mtrx_importance.ToString();
                String val2 = dat.Mtrx_magnitude.ToString();

                String iRef = new cecbClasses.Data_Adapters.ImpactAndActivity.Func_Impacts().findIref(impact);
                String aRef = new cecbClasses.Data_Adapters.ImpactAndActivity.Func_Impacts().findAref(activ);



                cecbClasses.Data_Adapters.Func_FillMatrix fillmx = new cecbClasses.Data_Adapters.Func_FillMatrix();
                if (fillmx.InsertValues(iRef, aRef, "PROJ1", val1, val2))
                {
                    var itemContainer =
                               listBoxEmailValues.ItemContainerGenerator.ContainerFromIndex(x) as ListBoxItem;
                    itemContainer.Background = Brushes.Green;

                }



            }
            catch (Exception)
            {

            }
        }

        private void button1_Click_1(object sender, RoutedEventArgs e)
        {
            SimpleMatrixlistBoxEmailValues.Visibility = System.Windows.Visibility.Visible;
            listBoxEmailValues.Visibility = System.Windows.Visibility.Hidden;
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            SimpleMatrixlistBoxEmailValues.Visibility = System.Windows.Visibility.Hidden;
            listBoxEmailValues.Visibility = System.Windows.Visibility.Visible;
        }

        private void ConfirmButton_Click(object sender, RoutedEventArgs e)
        {
            cecbClasses.Data_SimpleMatrixValues dat;
            dat = (cecbClasses.Data_SimpleMatrixValues)SimpleMatrixlistBoxEmailValues.SelectedItem;
            int x = SimpleMatrixlistBoxEmailValues.SelectedIndex;


            var itemContainer =
    SimpleMatrixlistBoxEmailValues.ItemContainerGenerator.ContainerFromIndex(x) as ListBoxItem;
            itemContainer.Background = Brushes.Green;


            //  MessageBox.Show(dat.Actv_reference.ToString());
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }






    }
    //============================================ Excell Reading ========================



    //====================================================================================




  


}
